package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.CustomException;
import com.reggie.dao.DishDao;
import com.reggie.dao.SetMealDao;
import com.reggie.dto.SetMealDto;
import com.reggie.pojo.Dish;
import com.reggie.pojo.Setmeal;
import com.reggie.pojo.SetmealDish;
import com.reggie.service.IDishService;
import com.reggie.service.ISetMealDishService;
import com.reggie.service.ISetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealDao, Setmeal> implements ISetMealService {

    @Autowired
    private ISetMealDishService setMealDishService;
    @Override
    @Transactional
    //保存有关联菜品的套餐
    public void saveWithDish(SetMealDto setMealDto) {//setMealDto 传过来的带菜品集合+分类名称 的套餐


        //保存没关联菜品的套餐信息
        this.save(setMealDto);
        //获取套餐中所关联的每个菜品的id,设置给每个套餐id
        //setmealDishes 套餐关联的菜品集合
        //setmealDish 套餐关联的每个菜品

        List<SetmealDish> setmealDishes = setMealDto.getSetmealDishes();
        setmealDishes.stream().map((setmealDish) -> {
            //套餐(setmeal表)的id 设置给 套餐关联的每个菜品(setmeal_dish表)的套餐id(setmeal_id)
            setmealDish.setSetmealId(setMealDto.getId());
            return setmealDish;
        }).collect(Collectors.toList());//返回关联好的菜品集合

        setMealDishService.saveBatch(setmealDishes);

    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，在售不能删(status == 1)
        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        slqw.in(Setmeal::getId,ids);
        slqw.eq(Setmeal::getStatus,1);
        if (this.count(slqw) >0){
            throw new CustomException("套餐正在售卖中，不可以删除");
        }
        //删除套餐数据(setmeal)
        this.removeByIds(ids);
        //删除套餐关联菜品数据(setmeal_dish)
        LambdaQueryWrapper<SetmealDish> sdlqw = new LambdaQueryWrapper<>();
        sdlqw.in(SetmealDish::getSetmealId,ids);
        setMealDishService.remove(sdlqw);
    }
}
